package ae.pcfc.cldos.online.common.manager.provider;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import ae.pcfc.cldos.online.common.manager.BaseManager;
import ae.pcfc.cldos.online.common.manager.FtlProcessorManager;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 
 * @author arosa
 *
 */
public class FtlProcessorManagerImpl extends BaseManager implements FtlProcessorManager, ApplicationContextAware {

	private ApplicationContext applicationContext;
	private Configuration fremarkerConfiguration;
	private String templateDir;
	
	public void setTemplateDir(String templateDir) {
		this.templateDir = templateDir;
	}
	
	public FtlProcessorManagerImpl(){
		fremarkerConfiguration = new Configuration();
		fremarkerConfiguration.setNumberFormat("0.#########");
		fremarkerConfiguration.setDefaultEncoding("UTF-8");
		fremarkerConfiguration.setDateFormat("dd/MM/yyyy");
		fremarkerConfiguration.setDateTimeFormat("dd/MM/yyyy HH:h:mm");
	}
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	public String processFtlTemplate(String templateName, Map<Object, Object> parameters) throws IOException, TemplateException{
		Template template = loadTemplate(templateName);
		StringWriter sw = new StringWriter();
		template.process(parameters, sw);
		return sw.toString();
	}
	
	public Template loadTemplate(String templateName) throws IOException{
		StringBuffer ftlFile = new StringBuffer(templateDir);
		ftlFile.append(templateName).append(".ftl");
		File templateFile = applicationContext.getResource(ftlFile.toString()).getFile();
		String fileName = templateFile.getName();
		String absolutePath = templateFile.getAbsolutePath();
		String dirPath = absolutePath.replace(fileName, "");
		File dir = new File(dirPath);
		fremarkerConfiguration.setDirectoryForTemplateLoading(dir);
		return fremarkerConfiguration.getTemplate(absolutePath.replace(dir.getAbsolutePath(), ""));
	}

}
